package as3.main 
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	/**
	 * Main Data
	 * @author cain in liontravel 2010
	 */
	public class MainData extends EventDispatcher
	{
		/**
		 * 資料準備好
		 */
		static public const DATA_READY:String = "Main_Data_DATA_READY";
		/**
		 * 撥放id變動
		 */
		static public const PLAY_ID_CH:String = "Main_Data_PLAY_ID_CH";
		
		private var _pcx_num:int;
		private var _pcx_path_vec:Vector.<String>;
		private var now_id:int = 1;
		private var _play_id:int;
		private var _path:String;
		/**
		 * Main Data
		 * @param	_dir 資料路徑
		 */
		public function MainData(_dir:String = "pcx")
		{
			_path = _dir;
			_pcx_path_vec = new Vector.<String>();
			load_dir();
		}
		/**
		 * 共有幾張圖
		 */
		public function get pcx_num():int 
		{
			return _pcx_num;
		}
		/**
		 * 圖檔路徑
		 * @param	_id 序號
		 * @return 圖檔路徑
		 */
		public function get_pcx_path(_id:int):String
		{
			if (_id>=_pcx_num) 
			{
				new Error("圖檔id超過");
			}
			return _pcx_path_vec[_id];
		}
		/**
		 * 撥放照片id
		 */
		public function set play_id(_id:int):void 
		{
			if (play_id!=_id) 
			{
				play_id = _id;
				dispatchEvent(new Event(PLAY_ID_CH));
			}
		}
		/**
		 * 撥放照片id
		 */
		public function get play_id():int 
		{
			return play_id;
		}
		/**
		 * 看看下一張是否存在
		 */
		private function load_dir():void
		{
			var _loader:Loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, _error);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, _loader_onPROGRESS);
			var _pcxpath:String = _path + "/" + now_id + ".jpg";
			_loader.load(new URLRequest(_pcxpath));
		}
		/**
		 * 沒有圖了 送出準備好
		 * @param	e
		 */
		private function _error(e:IOErrorEvent):void 
		{
			_pcx_num = now_id - 1;
			dispatchEvent(new Event(DATA_READY));
		}
		/**
		 * 存在則丟入_pcx_path_vec陣列
		 * @param	e
		 */
		private function _loader_onPROGRESS(e:ProgressEvent):void 
		{
			e.target.removeEventListener(ProgressEvent.PROGRESS, _loader_onPROGRESS);
			var _loader:Loader = Loader(e.target.loader);
			_loader.close();
			_loader.unload();
			_pcx_path_vec.push(LoaderInfo(e.target).loaderURL);
			now_id++;
			load_dir();
		}
	}

}